﻿<template>
  <div class="problem-sets-container">
    <!-- 页面头部 -->
    <div class="problem-sets-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="main-title">题目集管理</h1>
          <p class="subtitle">管理系统中的所有题目集，包括状态管理和删除操作</p>
        </div>
        <div class="stats-section">
          <div class="stat-item">
            <div class="stat-value">{{ total }}</div>
            <div class="stat-label">题目集总数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value active">{{ activeCount }}</div>
            <div class="stat-label">激活中</div>
          </div>
          <div class="stat-item">
            <div class="stat-value archived">{{ archivedCount }}</div>
            <div class="stat-label">已归档</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <div class="toolbar-left">
        <el-input
          v-model="searchParams.keyword"
          placeholder="搜索题目集名称..."
          prefix-icon="Search"
          clearable
          class="search-input"
          @input="handleSearch"
        />
        <el-select
          v-model="searchParams.status"
          placeholder="状态筛选"
          clearable
          class="filter-select"
          @change="handleSearch"
        >
          <el-option label="激活中" value="ACTIVE" />
          <el-option label="已归档" value="ARCHIVED" />
        </el-select>
      </div>
      <div class="toolbar-right">
        <el-button type="primary" @click="handleCreate">
          <el-icon class="el-icon--left"><Plus /></el-icon>
          创建题目集
        </el-button>
      </div>
    </div>

    <!-- 题目集列表 -->
    <div class="problem-sets-content" v-loading="loading">
      <div class="list-view">
        <el-table
          :data="problemSetList"
          class="problem-sets-table"
          @selection-change="handleSelectionChange"
          ref="problemSetTable"
          row-class-name="problem-set-row"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="id" label="#" width="80" align="center" />
          <el-table-column prop="name" label="题目集名称" min-width="250">
            <template #default="{ row }">
              <div class="problem-set-title-cell">
                <span class="title-text">{{ row.name }}</span>
                <div class="description-text" v-if="row.description">
                  {{ row.description.substring(0, 50) }}{{ row.description.length > 50 ? "..." : "" }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="可见性" width="100" align="center">
            <template #default="{ row }">
              <div class="status-pill" :class="row.isPublic ? 'visibility-public' : 'visibility-private'">
                {{ row.isPublic ? "公开" : "私有" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }">
              <div class="status-pill" :class="getStatusClass(row.status)">
                {{ getStatusText(row.status) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="成员" prop="memberCount" width="80" align="center" />
          <el-table-column label="题目" prop="problemCount" width="80" align="center" />
          <el-table-column label="创建者" prop="creatorName" width="120" align="center" show-overflow-tooltip />
          <el-table-column label="创建时间" prop="createdAt" width="180" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" align="center" fixed="right">
            <template #default="{ row }">
              <div class="operation-buttons">
                <el-button 
                  type="primary" 
                  link 
                  @click="handleViewDetail(row)" 
                  class="operation-button"
                >
                  查看详情
                </el-button>
                <el-button 
                  type="success" 
                  link 
                  @click="handleManageProblems(row)" 
                  class="operation-button"
                >
                  管理题目
                </el-button>
                <el-button 
                  type="warning" 
                  link 
                  @click="handleToggleStatus(row)" 
                  class="operation-button"
                >
                  {{ row.status === 'ACTIVE' ? '归档' : '激活' }}
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)" class="operation-button"> 删除 </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: "ProblemSetManagement",
};
</script>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { adminGetProblemSets, adminUpdateProblemSetStatus, adminDeleteProblemSet } from "@/api/modules/problem-set";

const router = useRouter();

// 响应式数据
const loading = ref(false);
const problemSetList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const selectedProblemSets = ref([]);
const problemSetTable = ref(null);

// 搜索参数
const searchParams = reactive({
  keyword: "",
  status: "",
});

// 统计数据
const activeCount = computed(() => problemSetList.value.filter(ps => ps.status === 'ACTIVE').length);
const archivedCount = computed(() => problemSetList.value.filter(ps => ps.status === 'ARCHIVED').length);

// 创建题目集
const handleCreate = () => {
  router.push("/admin/problemSet/create");
};

// 查看详情
const handleViewDetail = (row) => {
  router.push(`/problemSet/${row.id}`);
};

// 管理题目
const handleManageProblems = (row) => {
  router.push({
    path: `/problemSet/${row.id}`,
    query: { tab: 'problems' }
  });
};

// 加载题目集列表
const loadProblemSetList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams,
    };
    
    const response = await adminGetProblemSets(params);
    
    if (response.code === 200) {
      problemSetList.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || "获取题目集列表失败");
    }
  } catch (error) {
    ElMessage.error("获取题目集列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
  loadProblemSetList();
};

// 选择处理
const handleSelectionChange = rows => {
  selectedProblemSets.value = rows;
};

// 分页处理
const handleSizeChange = newSize => {
  pageSize.value = newSize;
  currentPage.value = 1;
  loadProblemSetList();
};

const handleCurrentChange = newPage => {
  currentPage.value = newPage;
  loadProblemSetList();
};

// 切换状态
const handleToggleStatus = async row => {
  const newStatus = row.status === 'ACTIVE' ? 'ARCHIVED' : 'ACTIVE';
  const actionText = newStatus === 'ARCHIVED' ? '归档' : '激活';
  
  try {
    await ElMessageBox.confirm(
      `确定要${actionText}题目集 "${row.name}" 吗？`,
      `${actionText}确认`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const response = await adminUpdateProblemSetStatus(row.id, newStatus);
    
    if (response.code === 200) {
      ElMessage.success(`${actionText}成功`);
      loadProblemSetList();
    } else {
      ElMessage.error(response.message || `${actionText}失败`);
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${actionText}失败`);
    }
  } finally {
    loading.value = false;
  }
};

// 删除题目集
const handleDelete = async row => {
  try {
    await ElMessageBox.confirm(
      `确定要删除题目集 "${row.name}" 吗？此操作不可恢复！`,
      "删除确认",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "error",
      }
    );

    loading.value = true;
    const response = await adminDeleteProblemSet(row.id);
    
    if (response.code === 200) {
      ElMessage.success("删除成功");
      loadProblemSetList();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

// 获取状态样式类
const getStatusClass = status => {
  return status === 'ACTIVE' ? 'status-active' : 'status-archived';
};

// 获取状态文本
const getStatusText = status => {
  return status === 'ACTIVE' ? '激活中' : '已归档';
};

// 格式化日期
const formatDate = date => {
  if (!date) return "";
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")} ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
};

// 组件挂载时加载数据
onMounted(() => {
  loadProblemSetList();
});
</script>

<style scoped lang="scss">
@use "@/styles/base/variables" as *;
@use "@/styles/base/mixins" as *;
@use "@/styles/pages/common" as *;

/* 使用统一的管理页面样式，只保留页面特定的样式 */
.problem-sets-container {
  @extend .admin-container;
  max-width: 1400px; // 题目集管理页面需要更宽
}

.problem-sets-header {
  @extend .admin-header;
}

.problem-sets-content {
  @extend .admin-content;
  min-height: 500px;

  .problem-sets-table {
    @extend .admin-table;
  }
}

.pagination-wrapper {
  @extend .admin-pagination;
}

/* 页面特定样式 */
.problem-set-title-cell {
  @extend .table-title-cell;
}
</style>
